package khiem.data.worldbank;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;

import khiem.data.worldbank.pojo.Source;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class SourcesQuery {
  private static final String requestURL = "http://api.worldbank.org/sources?format=json";
  
  public Source[] query() throws IOException {
    URL url = new URL(requestURL);
    URLConnection connection = url.openConnection();
    InputStream is = connection.getInputStream();

    StringBuilder result = new StringBuilder();
    Reader reader = new InputStreamReader(is);
    int c;
    while ((c=is.read()) != -1) {
      char ch = (char) c;
      result.append(ch);
    }
    reader.close();
    
    Gson gson = new Gson();
    JsonParser parser = new JsonParser();
    JsonElement element = parser.parse(result.toString());
    JsonArray array = element.getAsJsonArray();
    JsonObject info = array.get(0).getAsJsonObject();
    JsonElement jsonEle = array.get(1);
    Source[] sources = gson.fromJson(jsonEle, Source[].class);
    
    return sources;
  }
  
  public static void main(String[] args) throws IOException {
    new SourcesQuery().query();
  }

}
